<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>项目管理</title>
  <style type="text/css">
  	.red {
  		color: red;
  		font-size: 20px;
  		font-weight: bold;
  	}
  </style>
</head>
<body>
    <div class="wrapper">
    	<#include "../index/header.html">
   		<#include "../index/sidebar.html">
   		<div id="app" class="content">
   			 <div style="float:right;border:0px solid red;width:500px;"><el-button type="primary" @click="showDialogAddForm('add',null)">新增项目</el-button></div>
	     	 <el-table :data="tableData" style="width: 100%">
			    <el-table-column
			      label="项目名"
			      width="240">
			      <template slot-scope="scope">
			        <i></i>
			        {{ scope.row.name }}
			      </template>
			    </el-table-column>
			    <el-table-column
			      label="项目中文名"
			      width="220">
			      <template slot-scope="scope">
			        <i></i>
			        {{ scope.row.chineseName }}
			      </template>
			    </el-table-column>
			    <el-table-column
			      label="Git地址"
			      width="500">
			      <template slot-scope="scope">
			        <i></i>
			        {{ scope.row.gitUrl }}
			      </template>
			    </el-table-column>
			    <el-table-column label="操作">
			      <template slot-scope="scope">
			      	<el-button
			          size="mini"
			          @click="showDialogPublishForm(scope.row)">发布</el-button>
			        <el-button
			          size="mini"
			          @click="showDialogAddForm('edit',scope.row)">编辑</el-button>
		            <el-button
			          size="mini"
			          @click="showDialogBranchForm(scope.row)">分支</el-button>
			        <el-button
			          size="mini"
			          @click="showDialogPublishHistory(scope.row)">发布历史</el-button>
			      </template>
			    </el-table-column>
			  </el-table>
			  
			  <el-dialog title="发布历史" :visible.sync="dialogPublishHistoryVisible" center fullscreen>
				  <el-table :data="publishHistoryData">
				    <el-table-column property="date" label="分支" width="150">
				    	<template slot-scope="scope">
					        {{ scope.row.branch }}
					    </template>
				    </el-table-column>
				    <el-table-column property="name" label="发布时间" width="200">
				    	<template slot-scope="scope">
					        {{ scope.row.publishTimeText }}
					    </template>
				    </el-table-column>
				    <el-table-column property="name" label="发布人" width="200">
				    	<template slot-scope="scope">
					        尹吉欢
					    </template>
				    </el-table-column>
				    <el-table-column property="address" label="发布结果" width="200">
				    	 <template slot-scope="scope">
					        <el-popover trigger="hover" placement="top">
					          <p>{{ scope.row.errorMsg }}</p>
					          <div slot="reference" class="name-wrapper">
					            <el-tag size="medium" :type="scope.row.publishResultText == '失败' ? 'danger' : ''"> {{ scope.row.publishResultText }}</el-tag>
					          </div>
					        </el-popover>
					      </template>
				    </el-table-column>
				    <el-table-column property="address" label="发布机器" width="200">
				    	 <template slot-scope="scope">
					        <el-popover trigger="hover" placement="top">
					          <p v-for="m in scope.row.publishMachineList">{{m}}</p>
					          <div slot="reference" class="name-wrapper">
					            <el-tag size="medium">{{scope.row.publishMachineListCount}}台</el-tag>
					          </div>
					        </el-popover>
					      </template>
				    </el-table-column>
				    <el-table-column property="address" label="发布描述">
				    	<template slot-scope="scope">
					        {{ scope.row.publishDescribe }}
					    </template>
				    </el-table-column>
				    <el-table-column label="操作">
				      <template slot-scope="scope">
				      	<el-button v-show="scope.row.publishResultText == '成功'"
				          size="mini"
				          @click="showDialogPublishForm(scope.row)">回滚到该版本</el-button>
				      </template>
				    </el-table-column>
				  </el-table>
				  <div slot="footer" class="dialog-footer">
					  <el-pagination @current-change="publishHistoryPageChange"
						  background
						  layout="prev, pager, next"
						  :page-size="10"
						  :total="publishHistoryDataTotal">
						</el-pagination>
				  </div>
			  </el-dialog>
  
			  <el-dialog :title="dialogTitle" :visible.sync="dialogAddFormVisible" center>
				  <el-form :model="addForm" :rules="addFormRules" ref="addForm">
				     <el-form-item label="项目名" label-width="120px" prop="name">
					    <el-input v-model="addForm.name"></el-input>
					 </el-form-item>
					 <el-form-item label="中文名" label-width="120px" prop="chineseName">
					    <el-input v-model="addForm.chineseName"></el-input>
					 </el-form-item>
					 <el-form-item label="Git地址" label-width="120px" prop="gitUrl">
					    <el-input v-model="addForm.gitUrl"></el-input>
					 </el-form-item>
					 <el-form-item label="编译脚本" label-width="120px" prop="buildScript">
					    <el-input v-model="addForm.buildScript" placeholder="示例：/home/goojia/build.sh"></el-input>
					 </el-form-item>
					 <el-form-item label="钉钉Token" label-width="120px">
					    <el-input v-model="addForm.dingToken"></el-input>
					 </el-form-item>
				  </el-form>
				  <div slot="footer" class="dialog-footer">
				    <el-button @click="dialogAddFormVisible = false">取 消</el-button>
				    <el-button type="primary" @click="saveProject">确 定</el-button>
				  </div>
			  </el-dialog>
			  
			  <el-dialog title="分支管理" :visible.sync="dialogBranchFormVisible" center>
				  <el-form>
				     <el-form-item label="一行一个分支" label-width="120px" prop="name">
					    <el-input
						  type="textarea"
						  :autosize="{ minRows: 10, maxRows: 20}"
						  placeholder="请输入内容"
						  v-model="branchs">
						</el-input>
					 </el-form-item>
				  </el-form>
				  <div slot="footer" class="dialog-footer">
				    <el-button @click="dialogBranchFormVisible = false">取 消</el-button>
				    <el-button type="primary" @click="saveBranch">确 定</el-button>
				  </div>
			  </el-dialog>
			   
			  <el-dialog title="项目发布" :visible.sync="dialogPublishFormVisible" fullscreen center>
				  <el-form :model="publishForm" :rules="publishFormRules" ref="publishForm">
				    <el-form-item label="发布项目" label-width="140px">
				      {{publishForm.publishProjectName}}
				    </el-form-item>
				    <el-form-item label="编译后的程序路径" label-width="140px" prop="jarPath" style="width:1100px">
					    <el-input v-model="publishForm.jarPath" placeholder="示例：/home/goojia/viewstore/district-service/district-service-1.0.jar"></el-input>
					</el-form-item>
					<el-form-item label="启动脚本" label-width="140px" prop="deployScript" style="width:1100px">
					    <el-input v-model="publishForm.deployScript" placeholder="示例：/home/goojia/deploy.sh"></el-input>
					</el-form-item>
				    <el-form-item label="发布分支" label-width="140px"  prop="publishBranch">
				      <el-select v-model="publishForm.publishBranch" filterable placeholder="请选择"  style="width:960px">
					    <el-option
					      v-for="item in publishForm.publishBranchList"
					      :key="item.value"
					      :label="item.label"
					      :value="item.value">
					    </el-option>
					  </el-select>
				    </el-form-item>
				    
				    <el-form-item label="发布机器" label-width="140px" prop="publishMachineList">
				      <el-select v-model="publishForm.publishMachineList" filterable placeholder="请选择" multiple style="width:960px" >
					    <el-option
					      v-for="item in publishForm.machineList"
					      :key="item.value"
					      :label="item.label"
					      :value="item.value">
					    </el-option>
					  </el-select>
				    </el-form-item>
				    
				    <el-form-item label="发布描述" label-width="140px" style="width:1100px">
					    <el-input v-model="publishForm.publishDescribe" ></el-input>
					</el-form-item>
					
					<el-form-item label="执行状态" label-width="140px" class="red">
				      <el-tag type="danger" v-for="item in executeStatus">
				      	{{item}}
				      </el-tag>
				    </el-form-item>
				    
				    <el-form-item label="实时日志" label-width="140px">
				      <div style="height:500px;border:0px solid red;overflow-x:auto;overflow-y:auto;">
				      	<pre v-for="item in logs" :class="item.indexOf('error')>= 0 || item.indexOf('Exception') >= 0 ? 'red' : ''">{{item}}</pre>
				      </div>
				    </el-form-item>
				    
				  </el-form>
				  <div slot="footer" class="dialog-footer">
				    <el-button @click="dialogPublishFormVisible = false">取 消</el-button>
				    <el-button type="primary" @click="publishProject" :loading="publishProjectBtnLoading">确 定</el-button>
				  </div>
			   </el-dialog>
	    </div>
	    
    </div>
<script>
  new Vue({
    el: '#app',
    data: function() {
    	return {
    		publishProjectBtnLoading: false,
    		page: 1,
            tableData: [],
            publishHistoryData: [],
            publishHistoryDataTotal: 0,
            dialogPublishFormVisible: false,
            dialogAddFormVisible: false,
            dialogBranchFormVisible: false,
            dialogPublishHistoryVisible: false,
            publishForm: {
            	publishProjectName:'',
                publishBranch:'',
                publishBranchList:[],
            	publishMachineList:[],
            	machineList:[],
            	jarPath:'',
            	projectId: '',
            	deployScript: '',
            	publishDescribe: ''
            },
            addForm: {
            	id: '',
            	name: '',
            	chineseName: '',
            	gitUrl: '',
            	buildScript: '',
            	dingToken: ''
            },
            addFormRules: {
           	  name: [{ required: true, message: '请输入项目名', trigger: 'blur' }],
           	  chineseName: [{ required: true, message: '请输入中文名', trigger: 'blur' }],
              gitUrl: [{ required: true, message: '请输入Git地址', trigger: 'blur' }],
              buildScript: [{ required: true, message: '请输入编译脚本路径', trigger: 'blur' }]
            },
            publishFormRules: {
              publishBranch: [{ required: true, message: '请选择分支', trigger: 'blur' }],
              publishMachineList: [{ required: true, message: '请选择机器', trigger: 'blur' }],
              jarPath: [{ required: true, message: '请输入编译后的程序文件路径', trigger: 'blur' }],
              deployScript: [{ required: true, message: '请输入启动脚本', trigger: 'blur' }]
            },
            dialogTitle: "新增项目",
            handleDataUri: "/rest/project/add",
            logs: [],
            executeStatus: [],
            branchs: '',
            opId: ''
        }
    },
    mounted: function() {
    	this.queryProjectList();
    	this.queryMachineList();
    },
    methods:{
    	// 显示发布窗口
    	showDialogPublishForm: function(data) {
    		var that = this;
    		that.publishForm.projectId = data.id;
    		that.publishForm.publishProjectName = data.name;
    		that.dialogPublishFormVisible = true;
    		that.publishForm.publishBranchList = [];
    		that.publishForm.publishBranchList.push({value: 'master', label: 'master' });
    		if (data.branchs != "" && data.branchs != null) {
    			var branchList = data.branchs.split(',');
        		for(var i = 0;i < branchList.length; i++) {
        			var value = branchList[i];
        			that.publishForm.publishBranchList.push({value: value, label: value });
        		}
    		}
    		that.getLatelyPublishHistory();
    	},
    	showDialogPublishHistory: function(data) {
    		this.dialogPublishHistoryVisible = true;
    		this.queryPublishHistoryList(data.id, 1)
    	},
    	showDialogBranchForm: function(data) {
    		this.dialogBranchFormVisible = true;
    		this.opId = data.id;
    		if (data.branchs != null) {
    			this.branchs = data.branchs.replace(/,/g,"\n");
    		} else {
    			this.branchs = '';
    		}
    	},
    	saveProject: function() {
    		var that = this;
    		that.$refs['addForm'].validate((valid) => {
   	           if (valid) {
   	        	  axios.post(that.handleDataUri, that.addForm)
   	        	  .then(function (response) {
   	        	      if (response.data.code == 200) {
   	        	    	  that.$message({ message: '操作成功', type: 'success' });
   	        	    	  that.dialogAddFormVisible = false;
   	        	    	  that.queryProjectList();
   	        	      }
   	        	  })
   	        	  .catch(function (error) {
   	        		  if (error.response) {
   	   		     	      that.$message.error(error.response.data.message);
   	   		          } else {
   	   		        	  that.$message.error("网络异常");
   	   		          }
   	        	  });
   	           } else {
   	             return false;
   	           }
    	    });
    	},
    	queryProjectList: function() {
    		var that = this;
    		axios.get('/rest/project/list', {
    		    params: {
    		      page: that.page
    		    }
    		})
   		    .then(function (response) {
   		    	if (response.data.code == 200) {
   		    		that.tableData = response.data.data.list;
   		    	} else {
   		    		that.$message.error(response.data.message);
   		    	}
   		    })
   		    .catch(function (error) {
   		    	if (error.response) {
   		     	    that.$message.error(error.response.data.message);
   		        } else {
   		        	that.$message.error("网络异常");
   		        }
   		    });
    	},
    	showDialogAddForm: function(type, data) {
    		console.log(data)
    		if (type == 'add') {
    			this.dialogAddFormVisible = true;
    			this.addForm = {};
    			this.dialogTitle = "新增项目";
    			this.handleDataUri = "/rest/project/add";
    		} else {
    			this.dialogAddFormVisible = true;
    			this.addForm = data;
        		this.dialogTitle = "编辑项目";
        		this.handleDataUri = "/rest/project/edit";
    		}
    	},
    	publishProject: function () {
    		var that = this;
    		that.publishProjectBtnLoading = true;
    		that.$refs['publishForm'].validate((valid) => {
   	           if (valid) {
   	        	  var logsInterval = setInterval(function(){
    	    		  that.queryPublishLogs();
    	    	  },1000);
   	        	   axios.post('/rest/project/publish', that.publishForm)
	           	   .then(function (response) {
	           	      if (response.data.code == 200) {
	           	    	  var d = response.data.data;
	           	    	  if (d.result == 0) {
	           	    		 that.$message({ message: '操作成功', type: 'success' });
	           	    	  } else {
	           	    	 	 that.$message.error(d.msg);
	           	    	  }
	           	    	  setTimeout(function(){
	           	    		clearInterval(logsInterval);
	      	    	  	  },2000);
	           	    	  
	           	      } else {
	     		    	  that.$message.error(response.data.message);
	     		      }
	           	 	  that.publishProjectBtnLoading = false;
	           	    })
	          	   .catch(function (error) {
	          		  that.publishProjectBtnLoading = false;
	          		  if (error.response) {
  	   		     	      that.$message.error(error.response.data.message);
  	   		          } else {
  	   		        	  that.$message.error("网络异常");
  	   		          }
	          	   });
   	        	 
   	           } else {
   	             return false;
   	           }
    	    });
    	   
    	},
    	queryPublishLogs: function () {
    	   var that = this;
    	   axios.get('/rest/project/publish/logs', {
    		    params: {
    		       projectName: that.publishForm.publishProjectName,
    		       branch: that.publishForm.publishBranch
    		    }
    	   })
           .then(function (response) {
        	    if (response.data.code == 200) {
        	    	var list = response.data.data;
        	    	for (var i=0;i<list.length;i++) {
        	    		var log = list[i];
        	    		if (log != null && log != "" && log.indexOf(':ETAG:')>=0) {
        	    			that.executeStatus.push(log.substring(6));
        	    		}
        	    	}
        	    	that.logs = that.logs.concat(list);
        	    }
           })
       	   .catch(function (error) {
       		   console.log(error);
      		   if (error.response) {
      			  that.$message.error(error.response.data.message);
	           } else {
	        	  that.$message.error("网络异常");
	           }
       	   });
    	},
    	saveBranch: function () {
    		var that = this;
    		if(this.branchs != '') {
    			var branchs = that.branchs.split("\n").join(',');
	    		axios.post('/rest/project/branch', {branchs:branchs, projectId:that.opId})
	          	.then(function (response) {
	          	    if (response.data.code == 200) {
	          	    	that.$message({
   	        	          message: '操作成功',
   	        	          type: 'success'
   	        	        });
	          	    	that.dialogBranchFormVisible = false;
	          	    	that.queryProjectList();
	          	    }
	          	})
	         	.catch(function (error) {
	         		if (error.response) {
 	   		     	    that.$message.error(error.response.data.message);
 	   		        } else {
 	   		        	that.$message.error("网络异常");
 	   		        }
	         	});
    	    } else {
    	    	that.dialogBranchFormVisible = false;
    	    }
    	},
    	queryMachineList: function() {
    		var that = this;
    		that.publishForm.machineList = [];
     	    axios.get('/rest/machines')
            .then(function (response) {
         	    if (response.data.code == 200) {
         	    	var list = response.data.data;
         	    	for(var i = 0;i < list.length; i++) {
            			var value = list[i].id;
            			var label = list[i].intranetIp;
            			that.publishForm.machineList.push({value: value, label: label });
            		}
         	    }
            })
        	.catch(function (error) {
        		if (error.response) {
		     	    that.$message.error(error.response.data.message);
		        } else {
		        	that.$message.error("网络异常");
		        }
        	});
    	},
    	// 获取项目最近的发布历史
    	getLatelyPublishHistory: function() {
    		var that = this;
    		axios.get('/rest/publishHistory/lately', {
    		    params: {
    		    	projectId: that.publishForm.projectId
    		    }
    		})
   		    .then(function (response) {
   		    	if (response.data.code == 200) {
   		    		var history = response.data.data;
   		    		if (history != null) {
   		    			that.publishForm.jarPath = history.jarPath;
   	   		    		that.publishForm.deployScript = history.deployScript;
   	   		    		that.publishForm.publishBranch = history.branch;
   	   		    		that.publishForm.publishMachineList = history.publishMachines.split(',');
   		    		} else {
   		    			that.publishForm.jarPath = '';
   	   		    		that.publishForm.deployScript = '';
   	   		    		that.publishForm.publishBranch = '';
   	   		    		that.publishForm.publishMachineList = [];
   		    		}
   		    	} else {
   		    		that.$message.error(response.data.message);
   		    	}
   		    })
   		    .catch(function (error) {
   		    	if (error.response) {
   		     	    that.$message.error(error.response.data.message);
   		        } else {
   		        	that.$message.error("网络异常");
   		        }
   		    });
    	},
    	queryPublishHistoryList: function(projectId, page) {
    		var that = this;
    		that.opId = projectId;
     	    axios.get('/rest/publishHistory/list', {
     		    params: {
     		       projectId: projectId,
     		       page: page
     		    }
     	    })
            .then(function (response) {
         	    if (response.data.code == 200) {
         	    	var list = response.data.data.list;
         	    	that.publishHistoryData = list;
         	    	that.publishHistoryDataTotal = response.data.data.totalRecords;
         	    }
             })
        	 .catch(function (error) {
       		    if (error.response) {
       			   that.$message.error(error.response.data.message);
 	            } else {
 	        	   that.$message.error("网络异常");
 	            }
        	 });
    	},
    	publishHistoryPageChange: function(currentPage) {
    		this.queryPublishHistoryList(this.opId, currentPage);
    	}
    }
  })
</script>
</body>
</html>

